package chat.keepWind.event;

import java.net.InetSocketAddress;

import chat.keepWind.bean.DataPackage;
import chat.keepWind.handle.KeepWindEncoder;
import chat.keepWind.util.GlobalConst;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class SendMessage {
	
	public void send(final String remoteIp,DataPackage dataPkg) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //pipeline.addLast(new KeepWindDecoder()); //解密
                            pipeline.addLast(new KeepWindEncoder(new InetSocketAddress(remoteIp,GlobalConst.RCV_PORT))); //编码
                            //pipeline.addLast(new KeepWindInboundHandler());//处理数据
                        }
                    });
            Channel channel = bootstrap.bind(GlobalConst.SND_PORT).sync().channel();
            
            channel.writeAndFlush(dataPkg).sync();
            
            channel.closeFuture();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
